import {
  createRouter,
  createWebHashHistory
} from "vue-router";
import wise from "../utils/util";
import request from "../utils/request";
import {
  asyncRouterMap,
  constantRouterMap,
} from '@/plugins/router.config'
import store from '../store/index'


const routes = constantRouterMap


const router = createRouter({
  // history: createWebHistory(process.env.BASE_URL),
  history: createWebHashHistory(),
  routes,
});
let flag = 0
router.beforeEach((to, from, next) => {
  let token = localStorage.getItem('accesstoken') || ''
  //如果设置标题，拦截后设置标题
  if (to.meta.title) {
    document.title = to.meta.title
  }
  // 解决刷新页面空白问题
  if (flag === 0 && to.matched.length == 0) {
    flag++
    if (to.query) {
      router.push(to.fullPath);
    } else {
      router.push(to.path);
    }
  }

  // 无登录标识正常跳转页面
  if (to.path === "/login") {
    next();
  } else {
    if (token) {
      next();
    } else {
      next('/login')
    }
  }
})
const routerPackag = (routers, name) => {
  routers.forEach(itemRouter => {
    router.addRoute(name, itemRouter);
    // 是否存在子集
    if (itemRouter.children && itemRouter.children.length) {
      routerPackag(itemRouter.children, itemRouter.name);
    }
    return true;
  });
};
export function initRouterPath() {
  // 对路由规则进行路由的动态操作（权限过滤路由）
  // constantRouterMap[0].children
  const currentRouter = []
  const department = store.state.autoFindMenu
  let count = -1
  department.forEach((item, index) => {
    if (asyncRouterMap[item.id]) {
      count += 1
      currentRouter.push(asyncRouterMap[item.id])
      if (item.sonRule) {
        currentRouter[count].children = []
        item.sonRule.forEach((it, ind) => {
          if (asyncRouterMap[it.id]) {
            if (it.path) {
              asyncRouterMap[it.id].meta.path2 = it.path
            }
            currentRouter[count].children.push(asyncRouterMap[it.id])
          }
        })
      }
    }
  });

  // 添加动态路由到 router 内部（这时添加上去的路由还不能进行跳转）
  router.options.routes.some((item, index) => {
    if (item.name == 'index') {
      // 清空一下防止二次登录后出现重复 tab菜单 （页面从未出现刷新会出现）
      router.options.routes[index].children = []
      router.options.routes[index].children = [...router.options.routes[index].children, ...currentRouter]
      // 进入系统动态设置redirect页面
      // console.log(currentRouter[0]?.path, 'currentRouter[0]?.path');
      if (currentRouter[0]?.path) {
        let redirectRoot = {
          path: '/',
          redirect: currentRouter[0]?.meta?.isShowMenu ? currentRouter[1]?.path : currentRouter[0]?.path || ''
        }
        if (currentRouter[0]?.children && currentRouter[0]?.children.length > 0) {
          let redirectUrl = ''
          if (currentRouter[0]?.children[0].meta.isShowMenu) {
            // console.log(currentRouter[1]?.children,'hxshs');
            // redirectUrl = currentRouter[0]?.children[1].meta.path2 ? currentRouter[0]?.children[1].meta.path2 : currentRouter[0]?.children[1].path
            redirectUrl = (currentRouter[0]?.children && currentRouter[0]?.children.length > 1) ? currentRouter[0]?.children[1].meta.path2 : (currentRouter[0]?.children && currentRouter[0]?.children.length > 1) ? currentRouter[0]?.children[1].path : currentRouter[1]?.children[0].meta.path2
            if (currentRouter[0].children.length == 1 && currentRouter[0].children[0].meta.isShowMenu) {
              currentRouter[0].meta.isShowMenu = true
            }
          } else {
            redirectUrl = currentRouter[0]?.children[0].meta.path2 ? currentRouter[0]?.children[0].meta.path2 : currentRouter[0]?.children[0].path
          }
          redirectRoot = {
            path: '/',
            redirect: redirectUrl
          }
        }
        // 存在覆盖 不存在添加
        if (router.options.routes[0].path == '/') {
          router.options.routes[0] = redirectRoot
        } else {
          router.options.routes.unshift(redirectRoot)
        }
        router.addRoute(redirectRoot);
      }
      return true
    }
  })
  // 给每个路由添加进入路由这添加完成后即可进行跳转（addRoute添加路由到router上）
  routerPackag(currentRouter, "index");

}

export default router;